package com.briup.bookstore.service.impl;

import com.briup.bookstore.common.exception.ServiceException;
import com.briup.bookstore.common.response.ResultCode;
import com.briup.bookstore.domain.bean.User;
import com.briup.bookstore.domain.dto.UserLoginDTO;
import com.briup.bookstore.mapper.UserMapper;
import com.briup.bookstore.service.UserService;
import com.briup.bookstore.utils.JwtUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Map;

@Service
@RequiredArgsConstructor
public class UserServiceImpl implements UserService {

    private final UserMapper userMapper;

    @Override
    public Map<String, Object> login(UserLoginDTO loginDTO) {
        // 1. 确保用户名和密码是可用的
        String username = loginDTO.getUsername();
        check(username, ResultCode.USERNAME_IS_BLACK);
        String password = loginDTO.getPassword();
        check(password, ResultCode.PASSWORD_IS_BLACK);
        // 2. 根据用户名从数据库中获取用户数据
        User user = userMapper.queryByUsername(username);
        // 判断该用户对象是否为null
        if (user == null) {
            throw new ServiceException(ResultCode.USER_IS_NOT_EXISTS);
        }
        // 3. 判断用户密码是否输入正确
        if (!password.equals(user.getPassword())) {
            throw new ServiceException(ResultCode.PASSWORD_IS_ERROR);
        }
        // 4. 校验该账号是否可用
        if (user.getStatus() != 0) {
            throw new ServiceException(ResultCode.USER_STATUS_IS_FORBIDDEN);
        }
        // 在以上四步都无误的情况下，表示登录成功，就可以签发token
        String token = JwtUtil.sign(Map.of("userId", user.getId(),
                "username", user.getUsername()));
        // 返回token和对应的用户数据
        return Map.of("jwt", token, "userInfo", user);
    }

    @Override
    public User queryByUsername(String username) {
        return userMapper.queryByUsername(username);
    }

    @Override
    public User queryById(Integer userId) {
        return userMapper.queryById(userId);
    }

    private void check(String str, ResultCode resultCode) {
        if (!StringUtils.hasText(str)) {
            throw new ServiceException(resultCode);
        }
    }
}
